#include <iostream>

#include "memory/mempool/memory_pool.h"
#include "memory/metaspace.h"
#include "utilities/array.h" 
#include "utilities/globalDefinitions.h"
#include "classfile/classload.h"
#include "utilities/accessFlags.h"
#include "utilities/common.h"


void test_array(){
    Array<u1>* t = new (100) Array<u1>(100);
    t->at_put(0,1);
    t->at_put(1,2);
    INFO_PRINT("====array==> %d\n", t->at(0));
    INFO_PRINT("====array==> %d\n", t->at(1));

    Array<Method*>* ms = new (2) Array<Method*>(2);
    
    Method* m1 = new Method;
    Method* m2 = new Method;

    ms->at_put(0,m1);
    ms->at_put(1,m2);

    m1->set_name_index(10);
    m2->set_name_index(11);

    int l = ms->length();

    for(int i = 0 ; i< l ; i++){ 
           INFO_PRINT("====array[%d]==> %d\n",i , ms->at(i)->name_index());
    }


}

int main(int, char**) {
test_array();

    ClassLoader::initialize("/Users/bjliuyong/IdeaProjects/lemon-jvm/target/classes");

    InstanceKlass* klass = ClassLoader::load_classfile("com/lemon/jvm/example/AddAdd");

    const char* method_name = "main";
    const char* signature_name="([Ljava/lang/String;)V";


    Array<Method*>* _methods = klass->methods();
    int l = _methods->length();
    Method* main_method = NULL;
    for(int i = 0 ; i< l ; i++){
        Method* method = _methods->at(i);
        char* _method_name = klass->constants()->utf8_at(method->name_index());
        char* _signature_name = klass->constants()->utf8_at(method->signature_index());

        if(strcmp(method_name,_method_name) == 0 && strcmp(signature_name,_signature_name)==0)
        {
            main_method = method;
            break;
        }
        
    }

    //找到method


    char* us = klass->constants()->utf8_at(11);

    printf("us ==> %s\n", us);

    

    Metaspace::global_initialize();
    
    MetaWord* m = Metaspace::allocate(8);

    int* intp = (int*)m->ptr();
    
    *intp = 1100;
    printf("p_val ==> %d/n", m->value());

    std::cout << "Hello, world!\n";
}


/*
int main() {

    MemoryPool *mem_pool = new MemoryPool();

    MemoryChunk *mem_chunk = mem_pool->new_chunk(78 * 2);

    // 模拟分的内存超过Chunk的大小
//    mem_chunk->malloc(80);
//    mem_chunk->malloc(81);

    // 模拟内存足够，能分到内存
    MemoryCell *cell1 = mem_chunk->malloc(8);
    MemoryCell *cell2 = mem_chunk->malloc(16);
    MemoryCell *cell3 = mem_chunk->malloc(32);
    MemoryCell *cell4 = mem_chunk->malloc(16);

    *((char *) cell3->ptr()) = 'a';
    *((char *) cell1->ptr()) = 'c';
    INFO_PRINT("%X=====>%c, %c\n", cell3->ptr(), *((char *) cell3->ptr()), *((char *) cell1->ptr()));

    // 模拟GC后因内存碎片，分不到内存
    mem_chunk->malloc(40);

    INFO_PRINT("%X=====>%c, %c\n", cell3->ptr(), *((char *) cell3->ptr()), *((char *) cell1->ptr()));

    // 模拟出发第二次GC
//    mem_chunk->malloc(40);
//
//    INFO_PRINT("%X=====>%c, %c\n", cell3->ptr(), *((char *)cell3->ptr()), *((char *)cell1->ptr()));

    // mem_pool->print_chunks();

    delete mem_pool;

    return 0;
}
*/
